# -*- coding:utf-8 -*-

# 页面 crud 
from flask import Flask, request, render_template, flash, redirect, url_for
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired, Length
from flask_sqlalchemy import SQLAlchemy
import pymysql
pymysql.install_as_MySQLdb()

app = Flask(__name__)
app.secret_key = 'abc' # csrf token

# 数据库配置
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:@localhost:3306/test'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

# 初始化数据库
db = SQLAlchemy(app)

# 模型定义
class Car(db.Model):
    __tablename__ = 'cars'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(10))
    no = db.Column(db.String(8), unique=True)
    pId = db.Column(db.Integer, db.ForeignKey('drivers.id'))

    def __repr__(self):
        return f'({self.id},{self.name},{self.no})'

class Driver(db.Model):
    __tablename__ = 'drivers'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(10), unique=True)
    cars = db.relationship('Car', backref='owner')
    def __repr__(self):
        return f'({self.id},{self.name})'

def dataInit():
    db.drop_all() # 删除
    db.create_all() # 建表
    p = Driver(name='tom')
    db.session.add(p)
    db.session.commit()
    c1 = Car(name='BYD', no='LuQ:123', pId=p.id)
    c2 = Car(name='Bucket', no='LuQ:456', pId=p.id)
    c3 = Car(name='BYD', no='LuB:123', pId=p.id)
    db.session.add_all([c1,c2,c3])
    db.session.commit()

# 表单定义
class DriverForm(FlaskForm):
    username=StringField('username:', validators=[DataRequired()
        , Length(2,3,'username between 2-3 chars')])
    carName=StringField('car name:', validators=[DataRequired()])
    carNo=StringField('car number:', validators=[DataRequired()])
    submit=SubmitField('submit')

@app.route("/", methods=['GET','POST'])
def index():
    frm = DriverForm()
    if request.method == 'POST':
        if frm.validate_on_submit():
            uname = frm.username.data
            cname = frm.carName.data
            cno = frm.carNo.data
            u = Driver.query.filter_by(name=uname).first()
            if u:
                c = Car.query.filter_by(no=cno).first()
                if c:
                    flash(f'car already exist for driver {uname}')
                else:
                    db.session.add(Car(name=cname,no=cno,pId=u.id))
                    db.session.commit()
            else:
                u = Driver(name=uname)
                db.session.add(u)
                db.session.commit()
                db.session.add(Car(name=cname, no=cno, pId=u.id))
                db.session.commit()

    drivers = Driver.query.all()
    return render_template('car.html', frm=frm, drivers=drivers)

@app.route('/driver/del/<id>')
def delDriver(id):
    c = Driver.query.get(id)
    if c:
        db.session.delete(c)
        db.session.commit()
    # redirect('/') 与下面的等效
    # url_for('index') 得到的值就是路由函数上装饰器app.route中配置的uri
    return redirect(url_for('index')) # 跳转到index路由函数对应的uri地址上

@app.route('/car/del/<id>')
def delCar(id):
    Car.query.filter_by(id=id).delete()
    db.session.commit()
    return redirect('/')

if __name__ == '__main__':
    dataInit()
    app.run(debug=True)